package Java多线程和并发.Java并发线程基础;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2022-02-18 10:36
 **/
public class TestInterrupted {

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("Thread work is finished!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.start();
        // 在 main() 中启动一个线程之后再中断它，由于线程中调用了 Thread.sleep() 方法，因此会抛出一个 InterruptedException
        thread1.interrupt();
        System.out.println("Main is running……");

        Thread thread2 = new Thread(() -> {
            while (!Thread.interrupted()) {
                System.out.println("哈哈哈哈哈！");
            }
            System.out.println("Thread End!");
        });
        thread2.start();
        TimeUnit.SECONDS.sleep(1);
        thread2.interrupt();


        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<?> future = executorService.submit(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("Thread run");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        future.cancel(true);
        System.out.println("Main run");
    }
}
